package com.example.tutormanagement.filter;

import com.alibaba.fastjson.JSONObject;
import com.example.tutormanagement.pojo.Result;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.util.StringUtils;

import java.io.IOException;

/**
 * &#064;Date: 23/06/18-20:30
 * &#064;Description:
 */
//@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //前置：强制转换为http协议的请求对象、响应对象 （转换原因：要使用子类中特有方法）
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取请求url
        String url = request.getRequestURL().toString();

        //登录操作，放行 || url.contains("/tutor")
        if (url.contains("/login")) {
            filterChain.doFilter(request, response);//放行请求
            return;
        }
        //获取请求头中的token
        String token = request.getHeader("token");
        //判断令牌是否存在，如果不存在，返回错误结果（未登录）
        if (!StringUtils.hasLength(token)) {
            Result responseResult = Result.error("NOT_LOGIN");
            //把Result对象转换为JSON格式字符串(fastjson)
            String json = JSONObject.toJSONString(responseResult);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(json);
            return;
        }
        System.out.println(token);

        //解析token
        if (!token.equals("auth")) {
            Result responseResult = Result.error("NOT_LOGIN");
            String json = JSONObject.toJSONString(responseResult);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(json);
            return;
        }

        //放行
        filterChain.doFilter(request, response);
    }
}
